package com.hwadee.teachingprocessmanagementsystem.service.student.impl;

import com.hwadee.teachingprocessmanagementsystem.dto.DepartmentDto;
import com.hwadee.teachingprocessmanagementsystem.dto.student.*;
import com.hwadee.teachingprocessmanagementsystem.entity.*;
import com.hwadee.teachingprocessmanagementsystem.service.base.*;
import com.hwadee.teachingprocessmanagementsystem.service.student.StudentService;
import com.hwadee.teachingprocessmanagementsystem.util.ColorLoggerUtils;
import com.hwadee.teachingprocessmanagementsystem.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @Description: 学生服务接口实现类
 * @Author: Jukomu
 * @Package: com.hwadee.teachingprocessmanagementsystem.service.student.impl
 * @Project: TeachingProcessManagementSystem
 * @name: StudentServiceImpl
 * @Date: 2024/7/14-10:56
 * @Filename: StudentServiceImpl
 */
@Service("StudentService")
public class StudentServiceImpl implements StudentService {
    private ColorLoggerUtils logger = ColorLoggerUtils.getLogger(StudentServiceImpl.class);
    @Autowired
    private CourseClassesService courseClassesService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private CampusService campusService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private CourseChangeRequestService courseChangeRequestService;
    @Autowired
    private ClassroomRequestService classroomRequestService;
    @Autowired
    private ExamScheduleService examScheduleService;
    @Autowired
    private ExamMethodService examMethodService;
    @Autowired
    private AssessmentMethodService assessmentMethodService;
    @Autowired
    private ExamResultService examResultService;

    /**
     * 获取学生课程信息Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentCourseInfoDto getStudentCourseInfoDto(Student student) {
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(student);
        Set<String> set = new HashSet<>();
        List<Course> courseList = new ArrayList<>();
        for (CourseClasses courseClasses : courseClassesList) {
            String courseId = courseClasses.getCourseId();
            set.add(courseId);
        }
        for (String courseId : set) {
            Course course = this.courseService.queryById(courseId);
            courseList.add(course);
        }
        StudentCourseInfoDto studentCourseInfoDto = new StudentCourseInfoDto();
        studentCourseInfoDto.setStudentCourseList(courseList);
        return studentCourseInfoDto;
    }

    /**
     * 获取学生课表Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentScheduleInfoDto getStudentScheduleInfoDto(Student student) {
        StudentScheduleInfoDto studentScheduleInfoDto = new StudentScheduleInfoDto();
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(student);
        for (CourseClasses courseClasses : courseClassesList) {
            String courseId = courseClasses.getCourseId();
            Integer classroomId = courseClasses.getClassroomId();

            /**
             * 根据课程ID查询课程名和教师名
             */
            Course course = this.courseService.queryById(courseId);
            String courseName = course.getName();
            Integer courseLeaderId = course.getCourseLeaderId();
            Teacher teacher = this.teacherService.queryById(courseLeaderId);
            String teacherName = teacher.getName();
            /**
             * 根据教室ID查询教室位置
             */
            Classroom classroom = this.classroomService.queryById(classroomId);
            Integer campusId = classroom.getCampusId();
            Campus campus = this.campusService.queryById(campusId);
            String campusName = campus.getName();
            // 教室名称
            String location = classroom.getName();

            String weeks = courseClasses.getWeeks();
            String date = courseClasses.getDate();
            String time = courseClasses.getTime();

            studentScheduleInfoDto.addScheduleInfo(courseName, weeks, date, time, teacherName, campusName, location);
        }
        return studentScheduleInfoDto;
    }

    /**
     * 获取学生课程标准页面Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentCourseStandardDto getStudentCourseStandardDto(Student student) {
        StudentCourseStandardDto studentCourseStandardDto = new StudentCourseStandardDto();
        DepartmentDto departmentDto = this.departmentService.getDepartmentDto();
        studentCourseStandardDto.setDepartmentDto(departmentDto);

        // 查询学号对应学生选择的课程编号
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(student);
        List<String> courseIdList = new ArrayList<String>();
        for (CourseClasses courseClasses : courseClassesList) {
            String courseId = courseClasses.getCourseId();
            courseIdList.add(courseId);
        }

        // 遍历课程编号，获取开课单位、课程名称、学分、学时、课程类别
        for (String courseId : courseIdList) {
            Course course = this.courseService.queryById(courseId);
            Integer majorId = course.getMajorId();
            Major major = this.majorService.queryById(majorId);
            String departmentId = major.getDepartmentId();
            Department department = this.departmentService.queryById(departmentId);
            String departmentName = department.getName();
            String courseName = course.getName();
            Integer classHour = course.getClassHour();
            Integer credits = course.getCredits();
            String type = course.getType();
            studentCourseStandardDto.addStudentCourseStandard(departmentName, courseId, courseName, classHour, credits, type);
        }
        return studentCourseStandardDto;
    }

    /**
     * 获取学生课程标准页面Dto，查询范围为全部课程
     *
     * @param department
     * @param courseName
     * @param courseId
     * @return
     */
    @Override
    public StudentCourseStandardDto getStudentCourseStandardDto(String department, String courseName, String courseId) {
        StudentCourseStandardDto studentCourseStandardDto = new StudentCourseStandardDto();
        DepartmentDto departmentDto = this.departmentService.getDepartmentDto();
        studentCourseStandardDto.setDepartmentDto(departmentDto);

        // 查询所有课程班级信息
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(new Student());
        List<String> courseIdList = new ArrayList<String>();
        for (CourseClasses courseClasses : courseClassesList) {
            String courseId1 = courseClasses.getCourseId();
            courseIdList.add(courseId1);
        }

        // 遍历课程编号，获取开课单位、课程名称、学分、学时、课程类别
        for (String courseId2 : courseIdList) {
            // 指定课程编号
            if (!Objects.equals(courseId, "null") && !courseId.isEmpty()) {
                Course course = this.courseService.queryById(courseId);
                Integer majorId = course.getMajorId();
                Major major = this.majorService.queryById(majorId);
                String departmentId = major.getDepartmentId();
                Department department1 = this.departmentService.queryById(departmentId);
                String departmentName = department1.getName();
                String courseName1 = course.getName();
                Integer classHour = course.getClassHour();
                Integer credits = course.getCredits();
                String type = course.getType();
                studentCourseStandardDto.addStudentCourseStandard(departmentName, courseId, courseName1, classHour, credits, type);
                return studentCourseStandardDto;
            } else {
                // 没有指定课程编号
                System.out.println(courseId2);
                Course course = this.courseService.queryById(courseId2);
                Integer majorId = course.getMajorId();
                Major major = this.majorService.queryById(majorId);
                String departmentId = major.getDepartmentId();
                // 如果指定了系部
                if (!Objects.equals(department, "null") && !department.isEmpty()) {
                    if (department.equals(departmentId)) {
                        Department department1 = this.departmentService.queryById(departmentId);
                        String departmentName = department1.getName();
                        String courseName1 = course.getName();
                        if (courseName != null && !courseName.isEmpty()) {
                            if (courseName1.contains(courseName)) {
                                Integer classHour = course.getClassHour();
                                Integer credits = course.getCredits();
                                String type = course.getType();
                                studentCourseStandardDto.addStudentCourseStandard(departmentName, courseId2, courseName1, classHour, credits, type);
                                return studentCourseStandardDto;
                            }
                        }
                    }
                } else {
                    // 如果指定了名字
                    Department department1 = this.departmentService.queryById(departmentId);
                    String departmentName = department1.getName();
                    String courseName1 = course.getName();
                    if (!Objects.equals(courseName, "null") && !courseName.isEmpty()) {
                        if (courseName1.contains(courseName)) {
                            Integer classHour = course.getClassHour();
                            Integer credits = course.getCredits();
                            String type = course.getType();
                            studentCourseStandardDto.addStudentCourseStandard(departmentName, courseId2, courseName1, classHour, credits, type);
                            return studentCourseStandardDto;
                        }
                    }
                }
            }
        }
        return studentCourseStandardDto;
    }

    /**
     * 获取学生课件页面Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentCoursewareDto getStudentCourseWareDto(Student student) throws IOException {
        StudentCoursewareDto studentCoursewareDto = new StudentCoursewareDto();
        // 获取学生的课程信息
        StudentCourseInfoDto studentCourseInfoDto = this.getStudentCourseInfoDto(student);
        studentCoursewareDto.setStudentCourseInfoDto(studentCourseInfoDto);
        // 获取文件列表和目录列表
        // 遍历学生课程编号
        for (Course course : studentCourseInfoDto.getStudentCourseList()) {
            String courseId = course.getCourseId();
            String courseName = course.getName();
            Integer courseLeaderId = course.getCourseLeaderId();
            String teacherName = this.teacherService.queryById(courseLeaderId).getName();

            // 对每个课程编号查找目录下文件和子目录
            Map<String, List<File>> map = FileUtils.listFiles(new File("src/main/resources/static/courseware/"+courseId));
            List<File> fileList = new ArrayList<File>();
            List<File> pathList = new ArrayList<File>();
            if (map != null) {
                fileList = map.get("files");
                pathList = map.get("paths");
            }
            if (!fileList.isEmpty()) {
                for (File file : fileList) {
                    studentCoursewareDto.addFileInfo(
                            file.getName(),
                            file.length() / (1024),
                            String.valueOf((new Date(file.lastModified())).getTime()),
                            courseName,
                            teacherName,
                            file.getParentFile().getName()
                    );
                }
            }
            if (!pathList.isEmpty()) {
                for (File file : pathList) {
                    studentCoursewareDto.addPathInfo(
                            file.getName(),
                            String.valueOf((new Date(file.lastModified())).getTime()),
                            courseName,
                            file.getParentFile().getName()
                    );
                }
            }
        }
        return studentCoursewareDto;
    }

    /**
     * 获取学生调课Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentCourseChangeDto getStudentCourseChangeDto(Student student) {
        StudentCourseChangeDto studentCourseChangeDto = new StudentCourseChangeDto();
        StudentCourseInfoDto studentCourseInfoDto = getStudentCourseInfoDto(student);
        List<Course> studentCourseList = studentCourseInfoDto.getStudentCourseList();
        studentCourseList.forEach(item -> {
            Integer courseLeaderId = item.getCourseLeaderId();
            Teacher teacher = this.teacherService.queryById(courseLeaderId);
            String teacherName = teacher.getName();
            Integer teacherId = teacher.getTeacherId();
            String courseId = item.getCourseId();
            String courseName = item.getName();
            studentCourseChangeDto.addCourseTeacherInfo(courseId, courseName, String.valueOf(teacherId), teacherName);
        });
        List<CourseChangeRequest> courseChangeRequests = this.courseChangeRequestService.queryAllByStudentNumber(student);
        studentCourseChangeDto.setCourseChangeRequestList(courseChangeRequests);
        return studentCourseChangeDto;
    }

    /**
     * 获取学生教室申请Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentClassroomApplicationDto getStudentClassroomApplicationDto(String campusId, Student student) {
        StudentClassroomApplicationDto studentClassroomApplicationDto = new StudentClassroomApplicationDto();
        List<Campus> campuses = this.campusService.queryAllByLimit(new Campus());
        studentClassroomApplicationDto.setCampusList(campuses);
        ClassroomRequest classroomRequest = new ClassroomRequest();
        classroomRequest.setHeadPersonId(student.getStudentNumber());
        List<ClassroomRequest> classroomRequests = this.classroomRequestService.queryAllByLimit(classroomRequest);
        studentClassroomApplicationDto.setClassroomRequestList(classroomRequests);
        if (campusId == null) {
            studentClassroomApplicationDto.setClassesList(null);
        } else {
            Classroom classroom = new Classroom();
            classroom.setCampusId(Integer.valueOf(campusId));
            List<Classroom> classrooms = this.classroomService.queryAllByLimit(classroom);
            studentClassroomApplicationDto.setClassesList(classrooms);
        }
        return studentClassroomApplicationDto;
    }

    /**
     * 获取学生考试安排Dto
     *
     * @param student
     * @return
     */
    @Override
    public StudentExamArrangementDto getStudentExamArrangementDto(Student student) {
        StudentExamArrangementDto studentExamArrangementDto = new StudentExamArrangementDto();
        // 获取学生课程信息
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(student);
        Set<String> courseIds = new HashSet<>();
        for (CourseClasses courseClasses : courseClassesList) {
            // 遍历学生的所有课程，获取考试安排对象
            String courseId = courseClasses.getCourseId();
            courseIds.add(courseId);
        }
        for (String courseId : courseIds) {
            ExamSchedule examSchedule = this.examScheduleService.queryByCourseId(courseId);
            if (examSchedule != null) {
                Course course = this.courseService.queryById(courseId);
                String courseName = course.getName();
                Integer assessmentMethodId = course.getAssessmentMethodId();
                AssessmentMethod assessmentMethod = this.assessmentMethodService.queryById(assessmentMethodId);
                String assessmentMethodName = assessmentMethod.getName();
                Integer teacherId = course.getCourseLeaderId();
                Teacher teacher = this.teacherService.queryById(teacherId);
                String teacherName = teacher.getName();
                long timestamp = examSchedule.getDate().getTime();
                LocalTime startTime = examSchedule.getStartTime();
                LocalTime endTime = examSchedule.getEndTime();
                System.out.println(startTime);
                System.out.println(endTime);
                Integer classroomId = examSchedule.getClassroomId();
                Classroom classroom = this.classroomService.queryById(classroomId);
                String classroomName = classroom.getName();
                Integer campusId = classroom.getCampusId();
                Campus campus = this.campusService.queryById(campusId);
                String campusName = campus.getName();
                Integer examMethodId = examSchedule.getExamMethodId();
                ExamMethod examMethod = this.examMethodService.queryById(examMethodId);
                String methodName = examMethod.getName();
                studentExamArrangementDto.addStudentExamArrangementInfo(courseId, courseName, String.valueOf(teacherId), teacherName, String.valueOf(timestamp), startTime.toString(), endTime.toString(), campusName, classroomName, methodName, assessmentMethodName);
            }
        }
        return studentExamArrangementDto;
    }

    @Override
    public StudentExamResultDto getStudentExamResultDto(Student student) {
        StudentExamResultDto studentExamResultDto = new StudentExamResultDto();
        // 获取学生课程信息
        List<CourseClasses> courseClassesList = this.courseClassesService.queryAllByLimit(student);
        Set<String> courseIds = new HashSet<>();
        for (CourseClasses courseClasses : courseClassesList) {
            // 遍历学生的所有课程，获取考试安排对象
            String courseId = courseClasses.getCourseId();
            courseIds.add(courseId);
        }
        for (String courseId : courseIds) {
            // 学生课程对应的考试安排
            ExamSchedule examSchedule = this.examScheduleService.queryByCourseId(courseId);
            if (examSchedule != null) {
                Integer examId = examSchedule.getExamId();
                // 学生所有的考试成绩
                List<ExamResult> examResults = this.examResultService.queryByStudentNumber(student.getStudentNumber());
                for (ExamResult examResult : examResults) {
                    // 判断考试成绩和考试安排是否匹配
                    if (Objects.equals(examResult.getExamId(), examSchedule.getExamId())) {
                        Object score = examResult.getScore();
                        Course course = this.courseService.queryById(courseId);
                        String courseName = course.getName();
                        Integer assessmentMethodId = course.getAssessmentMethodId();
                        AssessmentMethod assessmentMethod = this.assessmentMethodService.queryById(assessmentMethodId);
                        String assessmentMethodName = assessmentMethod.getName();
                        Integer teacherId = course.getCourseLeaderId();
                        Teacher teacher = this.teacherService.queryById(teacherId);
                        String teacherName = teacher.getName();
                        long timestamp = examSchedule.getDate().getTime();
                        LocalTime startTime = examSchedule.getStartTime();
                        LocalTime endTime = examSchedule.getEndTime();
                        System.out.println(startTime);
                        System.out.println(endTime);
                        Integer classroomId = examSchedule.getClassroomId();
                        Classroom classroom = this.classroomService.queryById(classroomId);
                        String classroomName = classroom.getName();
                        Integer campusId = classroom.getCampusId();
                        Campus campus = this.campusService.queryById(campusId);
                        String campusName = campus.getName();
                        Integer examMethodId = examSchedule.getExamMethodId();
                        ExamMethod examMethod = this.examMethodService.queryById(examMethodId);
                        String methodName = examMethod.getName();
                        studentExamResultDto.addStudentExamArrangementInfo(courseId, courseName, String.valueOf(teacherId), teacherName, String.valueOf(timestamp), startTime.toString(), endTime.toString(), campusName, classroomName, methodName, assessmentMethodName,  ((Float)score).toString());
                    }
                }
            }

        }
        return studentExamResultDto;
    }
}
